<?php

defined('SYSPATH') or die('Access error!');

class Model_Ads extends Model
{

    public $rules = array(
        'name' => array
            (
            'not_empty' => null,
        )
    );

    /**
     * 后台需要的广告列表分页
     * @param type $where_arr
     * @return type
     */
    public function get_ads_list($where_arr = '',$nums = 10)
    {
        $where = " WHERE 1=1 ";
        if (Arr::validate_arr($where_arr))
        {
            if(isset($where_arr['category_id'])){
                $where .= ' AND a.category_id='.$where_arr['category_id'];
            }
            if(isset($where_arr['name'])){
                $where .= " AND a.name LIKE '%".$where_arr['name']."%'";
            }
        }
        $where .= ' ORDER BY a.position,a.id DESC';
        $sql = ' SELECT a.id,a.name,a.url,a.position,a.add_time,c.name as category_name ' .
                " FROM " . $this->table . " AS a " .
                " LEFT JOIN " . $this->db->get_table('category') . " AS c ON c.id = a.category_id " . $where;
        $data = $this->get_page_list($sql, $nums);
        return count($data) > 0 ? $data : array();
    }

    //获取某一个广告的详细内容
    public function get_ads_detail($id = 0)
    {
        $ads_detail = $this->get_row(array('id' => $id));
        if (Arr::validate_arr($ads_detail))
        {
            if (isset($ads_detail['file_name']))
            {
                $ads_detail['file_name'] = COMPONENT_ADS_IMAGES_PATH . '/' . $ads_detail['file_path'] . $ads_detail['file_name'];
            }
            return $ads_detail;
        }
        return array();
    }

    //根据广告的分类id获取广告
    public function get_ads_by_category_id($category_id, $ad_type = 1, $nums = 3)
    {
        $where = '  AND ad_type=' . $ad_type . ' AND category_id=' . $category_id . ' ORDER BY position,id DESC limit 5';

        $ads_list_temp = $this->get_results($where, 'name,file_name,file_path,url');
        $ads_list = array();
        if (Arr::validate_arr($ads_list_temp))
        {
            foreach ($ads_list_temp as $value)
            {
                $value['file_name'] = COMPONENT_ADS_IMAGES_PATH . '/' . $value['file_path'] . $value['file_name'];
                $ads_list[] = $value;
            }
        }

        return $ads_list;
    }

}